<template>
  <view :class="classArr">
    <template v-if="$slots.default">
      <slot></slot>
    </template>
    <template v-else>
      <template v-for="(_item, index) in controller.state.items" :key="index">
        <IBizRow :class="ns.b('content')" :layout="modelData.layout">
          <template v-for="panelItem in modelData.panelItems" :key="panelItem.id">
            <IBizCol
              :layoutPos="panelItem.layoutPos"
              :state="controller.dataItems[index].panelItems[panelItem.id!].state"
            >
              <template v-if="renderPanelItem">
                {{
                  renderPanelItem(panelItem, {
                    providers: controller.providers,
                    panelItems: controller.dataItems[index].panelItems,
                  })
                }}
              </template>
            </IBizCol>
          </template>
        </IBizRow>
      </template>
    </template>
  </view>
</template>

<script setup lang="ts">
import { IPanelItemProvider, IPanelItemController } from '@ibiz-template/runtime'
import { IPanelContainer, IPanelItem } from '@ibiz/model-core'
import { computed, inject, reactive, watch } from 'vue'
import { useNamespace } from '@/use'
import { MultiDataContainerController } from './i-biz-multi-data-container.controller'

const props = defineProps({
  modelData: {
    type: Object as PropType<IPanelContainer>,
    required: true,
  },
  controller: {
    type: MultiDataContainerController,
    required: true,
  },
})

const ns = useNamespace('multi-data-container')
const { id } = props.modelData

// 面板成员state响应式
watch(
  () => props.controller.state.items,
  () => {
    props.controller.dataItems.forEach((item) => {
      item.state = reactive(item.state)

      const keys = Object.keys(item.panelItems)
      keys.forEach((key) => {
        const panelItem = item.panelItems[key]
        panelItem.state = reactive(panelItem.state)
      })
    })
  },
  { immediate: true },
)

// 获取上层的绘制函数
const renderPanelItem = inject<
  (
    panelItem: IPanelItem,
    options?: {
      providers: {
        [key: string]: IPanelItemProvider
      }
      panelItems: {
        [key: string]: IPanelItemController
      }
    },
  ) => any
>('renderPanelItem')!

const classArr = computed(() => {
  const result: Array<string | false> = [ns.b(), ns.m(id), ...props.controller.containerClass]
  return result
})
</script>
<style lang="scss">
@import './i-biz-multi-data-container';
</style>
